package cn.zhihong.controller;

import cn.zhihong.common.R;
import cn.zhihong.dto.DishDto;
import cn.zhihong.pojo.Category;
import cn.zhihong.pojo.Dish;
import cn.zhihong.pojo.DishFlavor;
import cn.zhihong.service.CategoryService;
import cn.zhihong.service.DishFlavorService;
import cn.zhihong.service.DishService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName DishController
 * @Author 庄志宏
 * @Date 2022/4/23 11:02
 */
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    /**
     * @author 庄志宏
     * @date: 2022/4/23 11:03
     * 菜品管理分页查询
     */
    @Autowired
    private CategoryService categoryService;
    @GetMapping("/page")
    public R<Page> page(Integer page,Integer pageSize,String name){
        Page<Dish> pageInfo = new Page<>(page,pageSize);
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByDesc(Dish::getUpdateTime);
        lambdaQueryWrapper.like(StringUtils.isNotBlank(name),Dish::getName,name);
        dishService.page(pageInfo,lambdaQueryWrapper);
        Page<DishDto> dishDtoPage = new Page<>();
        List<DishDto> dishDtoList = new ArrayList<>();
        //对象拷贝
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");
        pageInfo.getRecords().forEach(record->{
            //获取分类id
            Long categoryId = record.getCategoryId();
            //通过分类id获取对于分类id的分类对象
            Category category = categoryService.getById(categoryId);
            //创建一个DishDto对象
            DishDto dishDto = new DishDto();
            if (category != null){
                //获取分类的名称
                String categoryName = category.getName();
                //给DishDto对象赋值分类名称
                dishDto.setCategoryName(categoryName);
            }
            //拷贝
            BeanUtils.copyProperties(record,dishDto);
            //把每一个DishDto对象都加到DishDto的list集合中
            dishDtoList.add(dishDto);
        });
        dishDtoPage.setRecords(dishDtoList);

        return R.success(dishDtoPage);
    }
    /**
     * @author 庄志宏
     * @date: 2022/4/23 17:02
     * 新增菜品
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        log.info("新增的菜品:{}",dishDto);
        dishService.saveWithFlavor(dishDto);
        return R.success("新增"+ dishDto.getName() +"菜品成功");
    }
    /**
     * @author 庄志宏
     * @date: 2022/4/24 12:12
     * 修改菜品，的回显数据
     */
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable("id") Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * @author 庄志宏
     * @date: 2022/4/24 12:35
     * 修改菜品信息
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        log.info("修改菜品信息{}",dishDto);
        dishService.updateWithFlavor(dishDto);
        return R.success("菜品信息修改成功");
    }
    /**
     * @author 庄志宏
     * @date: 2022/4/24 15:21
     * 根据id停售或启售菜品（单，批量都可以）
     */
    @PostMapping("/status/{status}")
    public R<String> status(@PathVariable("status") Integer status,Long[] ids){
        String name = status == 1 ?name="启售":"停售";
        for (Long id : ids){
            Dish dish = dishService.getById(id);
            dish.setStatus(status);
            dishService.updateById(dish);
        }
        return R.success("菜品" + name + "成功");
    }
    /**
     * @author 庄志宏
     * @date: 2022/4/24 15:32
     * 根据id删除菜品(单，批量都可以)
     */
    @DeleteMapping
    public R<String> delete(Long[] ids){
        dishService.removeWithFlavor(ids);
        return R.success("删除成功");
    }
    /**
     * @author 庄志宏
     * @date: 2022/4/25 15:25
     * 套餐管理添加菜品的回显各分类的菜品
     */
    /*@GetMapping("/list")
    public R<List<Dish>> list(Dish dish){
        log.info("套餐管理中，添加菜品回显菜品");
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.eq(dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());
        dishLambdaQueryWrapper.eq(Dish::getStatus,1);
        List<Dish> list = dishService.list(dishLambdaQueryWrapper);
        return R.success(list);
    }*/
    @GetMapping("/list")
    @Transactional
    public R<List<DishDto>> list(Dish dish){
        log.info("套餐管理中，添加菜品回显菜品");
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.eq(dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());
        dishLambdaQueryWrapper.eq(Dish::getStatus,1);
        List<Dish> list = dishService.list(dishLambdaQueryWrapper);


        List<DishDto> dishDtoList = list.stream().map(item->{
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if(category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId, dishId);
            List<DishFlavor> list1 = dishFlavorService.list(dishFlavorLambdaQueryWrapper);
            dishDto.setFlavors(list1);
            return dishDto;
        }).collect(Collectors.toList());
        return R.success(dishDtoList);
    }
}
